package com.matt.service.cookbook.impl;

import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.page.PagerQuery;
import com.matt.domain.simpleCookbook.SimpleCookbook;
import com.matt.foundation.model.ErrorCode;
import com.matt.repository.cookbook.SimpleCoookbookRepository;
import com.matt.service.UploadService;
import com.matt.service.cookbook.SimpleCookbookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

;

@Service
public class SimpleCookbookServiceImpl implements SimpleCookbookService {

    @Autowired
    SimpleCoookbookRepository baseRepository;

    @Autowired
    UploadService uploadService;

    @Override
    public SimpleCookbook get(StaffDTO staff, String id) {
        SimpleCookbook ret = baseRepository.getOneByIdAndAreaIdAndDeletedIsFalse(id, staff.getAreaId());

        if (ret == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "对象不存在");
        }

        return ret;
    }

    @Override
    public SimpleCookbook add(StaffDTO staff, String title, String content, MultipartFile image, Date beginAt, Date endAt) throws IOException {

//        String imageURL = uploadService.uploadSimpleCookbookImg(staff.getAreaId(), image);
        String imageURL = uploadService.uploadFileOss( image);

        SimpleCookbook ret = new SimpleCookbook();

        ret.setStaffId(staff.getId());
        ret.setAreaId(staff.getAreaId());
        ret.setTitle(title);
        ret.setDescription(content);
        ret.setBeginAt(beginAt);
        ret.setEndAt(endAt);
        ret.setResURL(imageURL);
        baseRepository.save(ret);

        return ret;
    }

    @Override
    public void deleteSimpleCookbook(StaffDTO staff, String id) {
        SimpleCookbook cookbook = get(staff, id);

        cookbook.setDeleted(true);

        baseRepository.save(cookbook);
    }

    @Override
    public Page<SimpleCookbook> page(String areaId, PagerQuery pagerQuery) {
        PageRequest pageRequest = PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize(), Sort.Direction.DESC, "created");
        return baseRepository.findAllByAreaIdAndDeletedIsFalse(areaId, pageRequest);
    }
}
